package design_patterns;

import java.util.ArrayList;
import java.util.List;

/**
 * 观察者模式
 * @author Fairy
 */
public class ObserverPattern {
    public static void main(String[] args) {
        ConcreteSubject s = new ConcreteSubject();
        s.attach(new ConcreteObserver("X", s));
        s.attach(new ConcreteObserver("Y", s));
        s.attach(new ConcreteObserver("Z", s));

        s.setSubjectState("ABC");
        s.toNotify();
    }
}

abstract class ObserverSubject {
    private List<Observer> observers = new ArrayList<>();
    public void attach(Observer observer) {
        observers.add(observer);
    }
    public void detach(Observer observer) {
        observers.remove(observer);
    }
    public void toNotify() {
        for (Observer o : observers) {
            o.update();
        }
    }
}
interface Observer {
    void update();
}
class ConcreteSubject extends ObserverSubject {
    private String subjectState;

    public String getSubjectState() {
        return subjectState;
    }

    public void setSubjectState(String subjectState) {
        this.subjectState = subjectState;
    }
}
class ConcreteObserver implements Observer {
    private String name;
    private String observerState;
    private ConcreteSubject subject;

    public ConcreteObserver(String name, ConcreteSubject subject) {
        this.name = name;
        this.subject = subject;
    }

    @Override
    public void update() {
        observerState = subject.getSubjectState();
        System.out.println("观察者"+name+"的新状态是"+observerState);
    }

    public String getObserverState() {
        return observerState;
    }

    public void setObserverState(String observerState) {
        this.observerState = observerState;
    }
}